<template>
  <my-table
    :tableObj="tableObj"
    row-key="id"
    default-expand-all
    v-loading="loading"
    class="org-table"
  >
    <template #prev>
      <el-table-column type="index" label="序号" width="200" />
    </template>
    <template #default>
      <el-table-column label="操作" align="left" header-align="left">
        <template #default="scope">
          <el-button type="primary" link @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-button type="success" link @click="handleAdd(scope.row)"
            >新增</el-button
          >
          <el-button type="danger" link @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </template>
  </my-table>
  <edit-add-form
    v-model="visible"
    :flag="flag"
    :formData="editFormData"
    @handleConfirm="handleConfirm"
  ></edit-add-form>
</template>
<script lang="ts" setup>
import EditAddForm from "./EditAddForm.vue";
import {
  updateOrganization,
  addOrganization,
  deleteOrganization,
} from "api/manage/manage";
import type { TableItem, TableData, EditForm, UpdateParams } from "../types";
import type { OrganizationId } from "api/manage/model/manage";
import { ElMessage } from "element-plus";
import { doApiWithMessageBox } from "utils/message";

interface Props {
  tableData: TableData;
  loading: boolean;
}
const props = defineProps<Props>();

interface Emits {
  (e: "handleSearch"): void;
}
const emit = defineEmits<Emits>();

const tableHeader = [
  {
    label: "名称",
    value: "name",
    align: "left",
  },
];
const tableObj = computed(() => ({
  tableData: props.tableData,
  tableHeader,
}));

const visible = ref<boolean>(false);
const flag = ref<"edit" | "add">("edit");
const editFormData = ref<EditForm>();
const handleEdit = (row: TableItem) => {
  visible.value = true;
  flag.value = "edit";
  editFormData.value = row;
};

let addParentId: OrganizationId = 0;
const handleAdd = (row: TableItem) => {
  visible.value = true;
  flag.value = "add";
  editFormData.value = {
    name: "",
  };
  addParentId = row.id;
};

const handleConfirm = async (params: EditForm) => {
  if (flag.value === "add") {
    // do add api
    await addOrganization({
      name: params.name,
      parentId: addParentId,
    });
    ElMessage({
      type: "success",
      message: "新增成功",
    });
    addParentId = 0;
  } else {
    // do edit api
    await updateOrganization(params as UpdateParams);
    ElMessage({
      type: "success",
      message: "修改成功",
    });
  }
  emit("handleSearch");
  visible.value = false;
};

const handleDelete = async (row: TableItem) => {
  await doApiWithMessageBox(() => deleteOrganization(row.id), {
    content: "确认删除该组织吗？",
  });
  emit("handleSearch");
};
</script>

<style lang="scss" scoped>
.org-table :deep(.el-table__cell) {
  text-align: left;
}
</style>
